package com.lry.basic.metrics;

import java.util.Arrays;

public class CompactSummary implements Summary{

    private final Id id;
    private final Id countId;
    private final Id totalId;
    private final Id tpsId;
    private volatile SummaryValue value;

    private final Clock clock;

    public CompactSummary(Id id){
        this(id,SystemClock.INSTANCE);
    }

    public CompactSummary(Id id,Clock clock){
        this.id = id;
        this.clock = clock;
        this.countId = new Id(id.getName()).withTag(id.getTags())
                .withTag(IdConstants.STATISTIC_KEY, IdConstants.STATISTIC_VALUE_COUNT);
        this.totalId = new Id(id.getName()).withTag(id.getTags())
                .withTag(IdConstants.STATISTIC_KEY, IdConstants.STATISTIC_VALUE_TOTAL);
        this.tpsId = new Id(id.getName()).withTag(id.getTags())
                .withTag(IdConstants.STATISTIC_KEY, IdConstants.STATISTIC_VALUE_TPS);
        this.value = new SummaryValue(clock.getCurrentMilliseconds());

    }

    @Override
    public Id getId() {
        return id;
    }

    @Override
    public Iterable<Measurement> measure() {
        SummaryValue value = this.value;
        double time = clock.getCurrentMilliseconds();
        this.value = new SummaryValue(time);

        return Arrays.asList(new Measurement(countId, time, value.getCount()),
                new Measurement(totalId, time, value.getTotal()),
                new Measurement(tpsId, time, value.getTps(time)));
    }

    @Override
    public void increase(long value) {
        this.value.increase(value);
    }

    @Override
    public long total() {
        return this.value.getTotal();
    }

    @Override
    public long count() {
        return this.value.getCount();
    }

    @Override
    public double tps() {
        return this.value.getTps(clock.getCurrentMilliseconds());
    }
}
